package com.liuyz.tcp_;

import org.junit.Test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TCP数据交互_字符流 {

    @Test
    public void server() throws IOException {
        ServerSocket serverSocket = new ServerSocket(9999);
        Socket socket = serverSocket.accept();

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 使用转换流构建字符流
        char[] arr = new char[1024];
        int len;
        while ((len = reader.read(arr)) != -1) {
            System.out.print(new String(arr, 0, len));
        }
        socket.shutdownInput(); // socket结束写入标记

        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 使用转换流构建字符流
        writer.write("hello,client");
        writer.flush(); // 字符流输出完成后手动刷新
        socket.shutdownOutput(); // socket结束写出标记

        writer.close(); // 关闭处理流即可
        reader.close(); // 关闭处理流即可
        socket.close();
        serverSocket.close();
    }

    @Test
    public void client() throws IOException {
        Socket socket = new Socket("127.0.0.1", 9999);
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); // 使用转换流构建字符流
        writer.write("hello,server");
        writer.flush(); // 字符流输出完成后手动刷新
        socket.shutdownOutput(); // socket结束写出标记

        BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // 使用转换流构建字符流
        char[] arr = new char[1024];
        int len;
        while ((len = reader.read(arr)) != -1) {
            System.out.print(new String(arr, 0, len));
        }
        socket.shutdownInput(); // socket结束写入标记

        reader.close(); // 关闭处理流即可
        writer.close(); // 关闭处理流即可
        socket.close();
    }

}
